package com.commun;

// import com.alpha.pt.Date;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import maps.test.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.PrayTime.PrayTime;
import com.PrayTime.PrayTimeLayout;
import com.PrayTime.PrayTime.EnumationPrayer;
import com.activity.MyMapActivity;
import com.calque.CalqueSites;
import com.calque.CalqueSitesClientTempMosqueAjouter;
import com.calque.CalqueSitesHavePicture;
import com.calque.MyPositionCalque;
import com.compass.Compass;
import com.data.DataBaseQuery;
import com.data.DataUtils;
import com.geo.MyMapView;
import com.google.android.maps.GeoPoint;
import com.object.Mosque;

public class Utils {
	public static List<Mosque> mosquais;
	public static boolean TOAST_TEXT_LAUNCHED = false;
	public static CalqueEnum calqueEnum;
	public static NotificationChoises notificationChoises;
	public static ProgressDialog dialogLoader;

	public enum CalqueEnum {
		HAVE_PICTURE_TEXT, PICTURE_SHOWN, NORMAL, TEMP_ITEMS, MEQUA,

	}

	public enum NotificationChoises {
		DESACTIVER, ACTIVER, ACTIVER_SON, ACTIVER_VIBRATION, ACTIVER_SON_VIBRATION

	}

	public static void RenitialiseMosquesMarqueurs() {
		DataBaseQuery bd = new DataBaseQuery();
		mosquais = bd.getAllMosquaisFromDataBase();
		if (mosquais.isEmpty())
			mosquais = bd.getAllMosquaisFromGoogleAPI();
		else
			mosquais.addAll(bd.getAllMosquaisFromGoogleAPI());

	}

	public static List<Mosque> getMosquais() {

		return mosquais;
	}

	public static void setMosquais(List<Mosque> mosquai) {
		mosquais = mosquai;
	}

	public static double deg2rad(final double deg) {
		return deg * Math.PI / 180;
	}

	public static float rad2deg(final double rad) {
		return (float) (rad * 180 / Math.PI);
	}

	public static String deg2str(final float rad) {
		return (int) rad + "�" + (int) ((Math.abs(rad) % 1) * 10000);
	}

	public static Integer str2int(final String str, final int defaut) {
		return str.matches("[0-9\\-]+") ? Integer.parseInt(str) : defaut;
	}

	public static String int2str(final Integer val) {
		return ((val < 10) ? "0" : "") + Integer.toString(val);
	}

	public static Location getCurrentLocation(final Context context) {
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setCostAllowed(true);

		LocationManager locationManager = (LocationManager) context
				.getSystemService(Context.LOCATION_SERVICE);
		Location currentLocation = null;
		try {
			currentLocation = locationManager
					.getLastKnownLocation(locationManager.getBestProvider(
							criteria, true));
			if (currentLocation == null) {
				criteria.setAccuracy(Criteria.ACCURACY_COARSE);
				currentLocation = locationManager
						.getLastKnownLocation(locationManager.getBestProvider(
								criteria, true));
			}
		} catch (Exception ex) {
			// GPS and wireless networks are disabled
		}
		return currentLocation;
	}

	public static boolean geoPointsAreSame(GeoPoint newMapCenter,
			GeoPoint oldMapCenter) {
		if (newMapCenter.getLatitudeE6() == oldMapCenter.getLatitudeE6()) {
			if (newMapCenter.getLongitudeE6() == oldMapCenter.getLongitudeE6()) {
				return true;
			}
		}
		return false;
	}

	public static Toast getMyCustomTextToast(Context context, String text) {

		LayoutInflater inflater = ((Activity) context).getLayoutInflater();
		View layout = inflater.inflate(R.layout.toast_layout,
				(ViewGroup) ((Activity) context)
						.findViewById(R.id.toast_layout_root));

		layout.setBackgroundDrawable(((Activity) context).getResources()
				.getDrawable(R.drawable.toast_layout_bg));
		TextView texts = (TextView) layout.findViewById(R.id.text);
		texts.setText(text);
		Toast toast = new Toast(((Activity) context).getApplicationContext());
		toast.setGravity(Gravity.CENTER, 0, 80);
		toast.setDuration(Toast.LENGTH_LONG);
		toast.setView(layout);

		return toast;
	}

	public static Toast getMyCustomImageShowToast(Context context, int resID) {
		Toast toast = new Toast(((Activity) context).getApplicationContext());
		toast.setGravity(Gravity.CENTER, 0, 0);
		LayoutInflater inflater = ((Activity) context).getLayoutInflater();
		View layout = inflater.inflate(R.layout.toast_picture_layout,
				(ViewGroup) ((Activity) context)
						.findViewById(R.id.toast_picture));
		ImageView imgView = (ImageView) layout
				.findViewById(R.id.image_mosque_view);
		imgView.setImageResource(resID);
		toast.setDuration(Toast.LENGTH_SHORT);

		toast.setView(layout);

		return toast;
	}

	public static MyMapView MapMarqueurSetup(MyMapView myMapView,
			Context context) {

		// calque normal sans image
		Drawable marqueur = ((Activity) context).getResources().getDrawable(
				R.drawable.brun_mosque);

		marqueur.setBounds(0, 0, marqueur.getIntrinsicWidth(), marqueur
				.getIntrinsicHeight());

		CalqueSites.InitialisationInsatance(marqueur, context, myMapView);
		myMapView.getOverlays().add(CalqueSites.getInstance());

		// calque avec image
		Drawable marqueurMosqueImage = ((Activity) context).getResources()
				.getDrawable(R.drawable.brun_mosque_image);

		marqueur.setBounds(0, 0, marqueurMosqueImage.getIntrinsicWidth(),
				marqueurMosqueImage.getIntrinsicHeight());
		CalqueSitesHavePicture.InitialisationInsatance(marqueurMosqueImage,
				context, myMapView);
		myMapView.getOverlays().add(CalqueSitesHavePicture.getInstance());

		// myCalquePosition
		Drawable marqueurMyPosition = ((Activity) context).getResources()
				.getDrawable(R.drawable.circle_blue);
		marqueurMyPosition.setBounds(0, 0, marqueurMyPosition
				.getIntrinsicWidth(), marqueurMyPosition.getIntrinsicHeight());

		myMapView.getOverlays().add(
				new MyPositionCalque(marqueurMyPosition, context));

		// le mosquer ajouter par le client
		Drawable marqueurTempClientMosquee = ((Activity) context)
				.getResources().getDrawable(R.drawable.blue_tag);

		marqueurTempClientMosquee.setBounds(0, 0, marqueurTempClientMosquee
				.getIntrinsicWidth(), marqueurTempClientMosquee
				.getIntrinsicHeight());
		CalqueSitesClientTempMosqueAjouter.InitialisationInsatance(
				marqueurTempClientMosquee, context, myMapView);
		myMapView.getOverlays().add(
				CalqueSitesClientTempMosqueAjouter.getInstance());

		return myMapView;
	}

	public static TabHost setupTabHost(final TabHost tabHost,
			final Context context) {

		tabHost.setup();

		tabHost.addTab(tabHost.newTabSpec("OngletSalatTime").setIndicator(
				"",
				((Activity) context).getResources().getDrawable(
						R.drawable.ic_tab_clock)).setContent(
				R.id.OngletSalatTime));

		tabHost
				.addTab(tabHost.newTabSpec("OngletMap").setIndicator(
						"",
						((Activity) context).getResources().getDrawable(
								R.drawable.ic_tab_location)).setContent(
						R.id.OngletMap));
		tabHost.addTab(tabHost.newTabSpec("OngletBoussole").setIndicator(
				"",
				((Activity) context).getResources().getDrawable(
						R.drawable.ic_tab_compass)).setContent(
				R.id.OngletBoussole));
		tabHost.addTab(tabHost.newTabSpec("OngletSetting").setIndicator(
				"",
				((Activity) context).getResources().getDrawable(
						R.drawable.ic_tab_setting)).setContent(
				R.id.OngletSetting));
		LinearLayout boussoleLinearLayout = (LinearLayout) ((Activity) context)
				.findViewById(R.id.OngletBoussole);

		boussoleLinearLayout.addView(new Compass(context));

		RelativeLayout prayTimeLayout = (RelativeLayout) ((Activity) context)
				.findViewById(R.id.OngletSalatTime);
		prayTimeLayout.addView(new PrayTimeLayout(context));

		for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
			tabHost.getTabWidget().getChildAt(i).setBackgroundColor(
					Color.parseColor("#808080"));

		}

		tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab())
				.setBackgroundColor(Color.parseColor("#ffcccccc"));

		tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
			public void onTabChanged(String tabId) {

				for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
					tabHost.getTabWidget().getChildAt(i).setBackgroundColor(
							Color.parseColor("#808080"));
				}
				tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab())
						.setBackgroundColor(Color.parseColor("#ffcccccc"));

				dismissToasts(context);

				if (tabHost.getCurrentTab() == 1 && DataBaseQuery.rayonChanged) {
					Double rayonState = Double.parseDouble(PreferenceManager
							.getDefaultSharedPreferences(
									MyMapActivity.getmContext()).getString(
									"rayon", "5"));
					if (DataBaseQuery.rayon != rayonState
							|| DataBaseQuery.firstResumeForMosquePosition) {
						DataBaseQuery.firstResumeForMosquePosition = false;
						final ProgressDialog dialogLoader = ProgressDialog
								.show(context, "", "Chargement...", true);

						dialogLoader.show();
						DataBaseQuery.rayon = rayonState;
						Handler mHandler = new Handler();
						Runnable mUpdateTimeTask = new Runnable() {
							public void run() {

								Utils.RenitialiseMosquesMarqueurs();
								CalqueSites.getInstance().Renitialise();
								CalqueSitesHavePicture.getInstance()
										.Renitialise();
								DataBaseQuery.rayonChanged = false;

								dialogLoader.dismiss();
								Utils.TOAST_TEXT_LAUNCHED = false;
							}
						};
						mHandler.removeCallbacks(mUpdateTimeTask);
						mHandler.postDelayed(mUpdateTimeTask, 2000);

					}
				}

			}
		});

		return tabHost;
	}

	public static void DelayTimer(final Context context, int time) {

		Handler mHandler = new Handler();
		Runnable mUpdateTimeTask = new Runnable() {
			public void run() {
				GetCutomize_layout_toast_outer_layout(context).setVisibility(
						View.VISIBLE);

				Utils.TOAST_TEXT_LAUNCHED = true;

			}
		};
		mHandler.removeCallbacks(mUpdateTimeTask);
		mHandler.postDelayed(mUpdateTimeTask, time);
	}

	public static RelativeLayout GetCutomize_layout_toast_outer_layout(
			final Context context) {
		return (RelativeLayout) ((Activity) context)
				.findViewById(R.id.cutomize_layout_toast_outer_layout);
	}

	public static RelativeLayout GetItem_update_layout(final Context context) {
		return (RelativeLayout) ((Activity) context)
				.findViewById(R.id.item_update_layout);
	}

	public final static int TIME_DELAYING = 200;

	public static void DisparitonLayoutImageTaost(final Context context) {

		Handler mHandler = new Handler();
		Runnable mUpdateTimeTask = new Runnable() {
			public void run() {

				GetCutomize_layout_toast_outer_layout(context).setVisibility(
						View.INVISIBLE);
				GetCutomize_layout_toast_outer_layout(context).setAlpha(1.0F);

				Utils.TOAST_TEXT_LAUNCHED = false;
			}
		};
		mHandler.removeCallbacks(mUpdateTimeTask);
		mHandler.postDelayed(mUpdateTimeTask, TIME_DELAYING);
	}

	public static void DisparitonLayoutTempItemTaost(final Context context) {

		Handler mHandler = new Handler();
		Runnable mUpdateTimeTask = new Runnable() {
			public void run() {

				GetItem_update_layout(context).setVisibility(View.INVISIBLE);
				GetItem_update_layout(context).setAlpha(1.0F);

				Utils.TOAST_TEXT_LAUNCHED = false;
			}
		};
		mHandler.removeCallbacks(mUpdateTimeTask);
		mHandler.postDelayed(mUpdateTimeTask, TIME_DELAYING);
	}

	public static void MyCustomisedViewToast(final Context context,
			final String text, final int resID) {

		RelativeLayout relativeLayout = Utils
				.GetCutomize_layout_toast_outer_layout(context);

		TextView texts = (TextView) relativeLayout
				.findViewById(R.id.cutomize_layout_toast_text);
		// texts = getArabicEnabledTextView(context, texts);
		texts.setText("   " + text + "  ");

		ImageButton imageButton = (ImageButton) relativeLayout
				.findViewById(R.id.cutomize_layout_toast_image);

		if (resID != -1) {

			imageButton.setImageResource(R.drawable.toast_image_botton);

			imageButton.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Utils.calqueEnum = CalqueEnum.PICTURE_SHOWN;

					CalqueSitesHavePicture.myToast = Utils
							.getMyCustomImageShowToast(context, resID);
					CalqueSitesHavePicture.myToast.show();

					Utils.GetCutomize_layout_toast_outer_layout(context)
							.setVisibility(View.INVISIBLE);
					Utils.TOAST_TEXT_LAUNCHED = true;

				}
			});

		} else {
			imageButton.setImageResource(R.drawable.transparent);

		}

		Handler mHandler = new Handler();
		Runnable mUpdateTimeTask = new Runnable() {
			public void run() {
				GetCutomize_layout_toast_outer_layout(context).setVisibility(
						View.VISIBLE);
				Utils.calqueEnum = CalqueEnum.HAVE_PICTURE_TEXT;

				Utils.TOAST_TEXT_LAUNCHED = true;

			}
		};
		mHandler.removeCallbacks(mUpdateTimeTask);

		mHandler.postDelayed(mUpdateTimeTask, TIME_DELAYING);

	}

	// #######
	public static void dismissToasts(Context mContext) {
		if (Utils.TOAST_TEXT_LAUNCHED) {
			switch (Utils.calqueEnum) {
			case NORMAL:
				Utils.DisparitonLayoutImageTaost(mContext);
				break;
			case TEMP_ITEMS:
				Utils.DisparitonLayoutTempItemTaost(mContext);
				break;
			case HAVE_PICTURE_TEXT:
				Utils.DisparitonLayoutImageTaost(mContext);
				break;
			case PICTURE_SHOWN:
				Utils.DisparitonLayoutImageTaost(mContext);

				CalqueSitesHavePicture.myToast.cancel();
				break;
			}
		}

	}

	public static String GetUniquePhoneID() {
		final TelephonyManager tm = (TelephonyManager) MyMapActivity
				.getmContext().getSystemService(Context.TELEPHONY_SERVICE);

		final String tmDevice, tmSerial, androidId;
		tmDevice = "" + tm.getDeviceId();
		tmSerial = "" + tm.getSimSerialNumber();
		androidId = ""
				+ android.provider.Settings.Secure.getString(MyMapActivity
						.getmContext().getContentResolver(),
						android.provider.Settings.Secure.ANDROID_ID);

		UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice
				.hashCode() << 32)
				| tmSerial.hashCode());
		return deviceUuid.toString();

	}

	public static void AlertTestDeveloppementMsg(String text) {
		AlertDialog.Builder builder = new AlertDialog.Builder(MyMapActivity
				.getmContext());

		builder.setMessage(text).setCancelable(false).setPositiveButton("Yes",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				}).setNegativeButton("No",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}

	private static final String FONTS_LOCATION_PATH = "fonts/DejaVuSans.ttf";

	public static TextView getArabicEnabledTextView(Context context,
			TextView targetTextView) {
		// this is a static for testing!
		Typeface face = Typeface.createFromAsset(context.getAssets(),
				FONTS_LOCATION_PATH);
		targetTextView.setTypeface(face);

		return targetTextView;
	}
	public static EnumationPrayer ChekPrayTime() {

		ArrayList<String> prayTime = PrayTime.getInstance().GetPrayTimeStringsCustom(
				PreferenceManager.getDefaultSharedPreferences(
						MyMapActivity.getmContext()).getInt(
						"pray_time_cal_meth", 0));
		Date now = new Date();
		Calendar cal = Calendar.getInstance();
		cal.setTime(now);

		// if(true ){
		// cal.set(Calendar.HOUR_OF_DAY,3);
		// cal.set(Calendar.MINUTE,57);
		// }

		int houre = cal.get(Calendar.HOUR_OF_DAY);
		int minuts = cal.get(Calendar.MINUTE);

		String fajr = prayTime.get(0).trim();
		String dhohr = prayTime.get(2).trim();
		String asr = prayTime.get(3).trim();
		String maghreb = prayTime.get(4).trim();
		String isha = prayTime.get(6).trim();

		if ((Integer.parseInt(fajr.substring(0, 2)) == houre)
				&& (Integer.parseInt(fajr.substring(3, 5)) == minuts))
			return EnumationPrayer.FAJR;
		if ((Integer.parseInt(dhohr.substring(0, 2)) == houre)
				&& (Integer.parseInt(dhohr.substring(3, 5)) == minuts))
			return EnumationPrayer.DHOHR;
		if ((Integer.parseInt(asr.substring(0, 2)) == houre)
				&& (Integer.parseInt(asr.substring(3, 5)) == minuts))
			return EnumationPrayer.ASR;
		if ((Integer.parseInt(maghreb.substring(0, 2)) == houre)
				&& (Integer.parseInt(maghreb.substring(3, 5)) == minuts))
			return EnumationPrayer.MAGHREB;
		if ((Integer.parseInt(isha.substring(0, 2)) == houre)
				&& (Integer.parseInt(isha.substring(3, 5)) == minuts))
			return EnumationPrayer.ISHA;

		return EnumationPrayer.NO_ONE;
	}

}